package top.stacktrace.gateway.service;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import top.stacktrace.account.domain.LoginVo;
import top.stacktrace.account.domain.User;
import top.stacktrace.gateway.config.auth.AuthException;
import top.stacktrace.gateway.config.auth.Token;
import top.stacktrace.gateway.config.auth.TokensAuthority;
import top.stacktrace.gateway.config.auth.UserToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Service
public class LoginService {
    @Autowired
    private AccountFeign accountFeign;
    @Autowired
    private LoginCacheService loginCacheService;

    public Token login(LoginVo v) {
        User u = accountFeign.checkLogin(v);
        String token = IdUtil.fastSimpleUUID();
        Token t = loginCacheService.makeToken(token,u);
        if(t.isAuthenticated()) {
            this.removeUserToken(t.getUserid());
            loginCacheService.saveUser(t.getToken(), t.getUserid());
        }
        return t;
    }

    public void removeUserToken(long userid){
        UserToken userToken = loginCacheService.getUserToken(userid);
        if(Objects.nonNull(userToken)){
            loginCacheService.removeToken(userToken.getToken());
        }
        loginCacheService.delUserToken(userid);
    }

    public void removeToken(String token){
        loginCacheService.removeToken(token);
    }

    public Token getToken(String token){
        return loginCacheService.getToken(token);
    }
}
